package com.plian.system.controller.form;

import com.alibaba.fastjson.JSONObject;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ObjResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * 表单统一入口
 */
@Slf4j
@RestController
@RequestMapping("api/form")
public class FormController {

    /**
     * 列表
     * @param pd
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    public Object listpage(@RequestBody PageData pd,HttpServletRequest request) {
       String url= request.getRequestURL().toString();
        url=url.replace("form/listPage","");
        String formType = pd.getString("formType");
        Object object=new Object();
        //产权登记
       if(formType.equals(String.valueOf(FormTypeConstant.PM_PROPERTY_FORM))){
             url+="property/list";
       }
       //产权变动
       else if(formType.equals(String.valueOf(FormTypeConstant.PM_PROPERTYCHANGE_FORM))){
           url+="propertyChange/listPage";
       }
       //产权注销
       else if(formType.equals(String.valueOf(FormTypeConstant.PM_PROPERTYOUT_FORM))){
           url+="propertyChange/listPage";
       }
       else{
           ObjResult objResult=   new ObjResult(CommonCode.ERROR);
           objResult.setMessage("未知表单类型!!!");
           throw new MyRuntimeException(objResult);
       }

        try {
            object=sendPost(url,new JSONObject(pd),"utf-8",request);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return JSONObject.parse(object.toString());
    }

    @RequestMapping(value = "/save")
    public Object save(@RequestBody PageData pd,HttpServletRequest request) {
        String url= request.getRequestURL().toString();
        url=url.replace("form/listPage","");
        String formType = pd.getString("formType");
        Object object=new Object();
        //产权登记
        if(formType.equals(String.valueOf(FormTypeConstant.PM_PROPERTY_FORM))){
            url+="property/save";
        }
        //产权变动
        else if(formType.equals(String.valueOf(FormTypeConstant.PM_PROPERTYCHANGE_FORM))){
            url+="propertyChange/save";
        }
        //产权注销
        else if(formType.equals(String.valueOf(FormTypeConstant.PM_PROPERTYOUT_FORM))){
            url+="propertyChange/save";
        }
        else{
            ObjResult objResult=   new ObjResult(CommonCode.ERROR);
            objResult.setMessage("未知表单类型!!!");
            throw new MyRuntimeException(objResult);
        }

        try {
            object=sendPost(url,new JSONObject(pd),"utf-8",request);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return JSONObject.parse(object.toString());
    }

    @RequestMapping(value = "/edit")
    public Object edit(@RequestBody PageData pd,HttpServletRequest request) {
        String url= request.getRequestURL().toString();
        url=url.replace("form/listPage","");
        String formType = pd.getString("formType");
        Object object=new Object();
        //产权登记
        if(formType.equals(String.valueOf(FormTypeConstant.PM_PROPERTY_FORM))){
            url+="property/edit";
        }
        //产权变动
        else if(formType.equals(String.valueOf(FormTypeConstant.PM_PROPERTYCHANGE_FORM))){
            url+="propertyChange/edit";
        }
        //产权注销
        else if(formType.equals(String.valueOf(FormTypeConstant.PM_PROPERTYOUT_FORM))){
            url+="propertyChange/edit";
        }
        else{
            ObjResult objResult=   new ObjResult(CommonCode.ERROR);
            objResult.setMessage("未知表单类型!!!");
            throw new MyRuntimeException(objResult);
        }
        try {
            object=sendPost(url,new JSONObject(pd),"utf-8",request);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return JSONObject.parse(object.toString());
    }

    private Object sendPost(String url,JSONObject jsonObject,String encoding,HttpServletRequest request) throws IOException {
        CloseableHttpResponse response = null;
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig config=RequestConfig.custom()
                .setConnectTimeout(60000) // 设置连接超时时间 3秒钟
                .setSocketTimeout(180000) // 设置读取超时时间0.01秒钟
                .build();
        httpPost.setConfig(config);
        httpPost.setEntity(new StringEntity(jsonObject.toString()));
        httpPost.setHeader("Content-type", "application/json;charset=UTF-8 ");
        httpPost.setHeader("token", request.getHeader("token"));
        response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String body="";
        if (entity != null) {
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        response.close();
        return body;
    }
}
